import { LockOutlined, UserOutlined } from '@ant-design/icons'
import { Alert, Button, Card, Form, Input, Typography } from 'antd'
import { useState } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { ROUTES } from '@router/paths'
import { useAuth } from '@store/AuthProvider'
import styles from './login.module.css'

type LoginFormValues = {
  username: string
  password: string
}

const LoginPage = () => {
  const [error, setError] = useState<string | null>(null)
  const [loading, setLoading] = useState(false)
  const navigate = useNavigate()
  const location = useLocation()
  const { login } = useAuth()

  const handleFinish = async (values: LoginFormValues) => {
    try {
      setLoading(true)
      setError(null)

      const result = await login(values)

      const redirect =
        (location.state as { from?: string } | undefined)?.from || ROUTES.dashboard

      navigate(redirect, { replace: true, state: { user: result.user } })
    } catch (err) {
      setError(err instanceof Error ? err.message : '登录失败，请重试')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className={styles.container}>
      <Card className={styles.card}>
        <Typography.Title level={3} className={styles.title}>
          React 管理系统
        </Typography.Title>
        <Typography.Paragraph type="secondary" className={styles.subtitle}>
          请输入账号密码进入控制台示例，默认账号：admin / 123456
        </Typography.Paragraph>

        {error ? (
          <Alert
            className={styles.alert}
            message="登录失败"
            description={error}
            type="error"
            showIcon
          />
        ) : null}

        <Form<LoginFormValues>
          className={styles.form}
          layout="vertical"
          initialValues={{ username: 'admin', password: '123456' }}
          onFinish={handleFinish}
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input prefix={<UserOutlined />} placeholder="admin" />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password prefix={<LockOutlined />} placeholder="123456" />
          </Form.Item>

          <Button
            className={styles.submitButton}
            type="primary"
            htmlType="submit"
            block
            size="large"
            loading={loading}
          >
            登录
          </Button>
        </Form>
      </Card>
    </div>
  )
}

export default LoginPage


